﻿using BestHTTP;
using Com.Shinian.FcgProtocol.Pb;
using FCG.cache.proxy_model;
using GF.Debug;
using GFFramework.UI;
using Network;
using pEventBus;
using System;
using UnityEngine.UI;

[UI((int)WinEnum.Win_FCGLogin, "Windows/LoginPanel")]
public class CUIFCGLoginWindow : WindowBase,
    IEventReceiver<WSHandShakeSuccessEvent>,
    IEventReceiver<StaticDataLoadSuccessEvent>
{
    [TransformPath("StartButton")] private Button btn_Start;
    [TransformPath("PasswordInputField")] private InputField ifd_Password;
    [TransformPath("UsernameInputField")] private InputField ifd_UserName;
    [TransformPath("Dropdown")] private Dropdown ddn_ServerList;
    bool load = false;
    string userName = "", password = "", nickName = "", club = "";

    public CUIFCGLoginWindow(string path) : base(path)
    {

    }

    public override void Init()
    {
        base.Init();
        EventBus.Register(this);
        AudioMgr.StopBGM();
        NetMgr.Register(ProxyModelIndex.PlayerPM, OnPlayerPMUpdate);
        btn_Start.onClick.AddListener(delegate ()
        {
            if (ifd_UserName.text != "" && ifd_Password.text != "")
            {
                Login(ifd_UserName.text, ifd_Password.text, "aladdin", "20001");
            }
        });
        LoadServerList();
    }

    public override void Open(WindowData data = null)
    {
        base.Open(data);
    }

    public void LoadServerList()
    {
        ddn_ServerList.ClearOptions();
        if (StaticDataUtil.instance.serverListDTO != null)
        {
            for (int i = 0; i < StaticDataUtil.instance.serverListDTO.LoginNodes.Count; i++)
            {
                LoginNodeDTO loingNodeDTO = StaticDataUtil.instance.serverListDTO.LoginNodes[i];
                Dropdown.OptionData optionData = new Dropdown.OptionData();
                string[] t = loingNodeDTO.LoginAPI.Split('@');
                optionData.text = t[t.Length - 1];
                GF.Debug.Debugger.Log("loginNodeUrl:" + optionData.text);
                ddn_ServerList.options.Add(optionData);
            }
            ddn_ServerList.value = 0;
        }
    }

    public void Login(string userName, string password, string nickName, string club)
    {
        if (userName.Length == 0 || password.Length == 0 || nickName.Length == 0 || club.Length == 0) return;
        Uri loginUrl = new Uri(ddn_ServerList.options[ddn_ServerList.value].text + "?p=" + DateTime.UtcNow.Ticks);
        HTTPRequest req = new HTTPRequest(loginUrl, HTTPMethods.Get, (reqEnd, respEnd) =>
        {
            //Debug.Log("HTTP<api/login> StatusCode:" + respEnd.StatusCode);
            if (respEnd.StatusCode == 200)
            {
                GF.Debug.Debugger.Log("登录成功");
                LoginResultDTO loginResultDTO = LoginResultDTO.Parser.ParseFrom(respEnd.Data);
                //Debug.Log("LoginResultDTO" + loginResultDTO);
                if (loginResultDTO.LoginCode == (int)LoginResultCodeType.LoginSuccess ||
                    loginResultDTO.LoginCode == (int)LoginResultCodeType.NewUser)
                {
                    WebSocketConnect.instance.lobbyLogin(
                        loginResultDTO.LobbyNodeIp,
                        loginResultDTO.LobbyNodePort,
                        loginResultDTO.Uid,
                        loginResultDTO.Token.ToByteArray());
                }
            }
        });
        req.AddField("USERNAME", userName);
        req.AddField("PASSWORD", password);
        req.AddField("NICKNAME", nickName);
        req.AddField("CLUB", club);
        req.Timeout = TimeSpan.FromMilliseconds(3000);
        req.ConnectTimeout = TimeSpan.FromMilliseconds(3000);
        req.DisableCache = true;
        req.Send();
    }

    void OnPlayerPMUpdate(ProxyModelUpdateEvent bubbleevent)
    {
        //登陆成功跳转
        Debugger.Log("登陆成功");
        UIManager.Inst.LoadWindows((int)WinEnum.Win_Home);
        UIManager.Inst.ShowWindow((int)WinEnum.Win_Home);
    }

    public void OnEvent(WSHandShakeSuccessEvent e)
    {
        WebSocketConnect.instance.Pack((short)FCGChannel.ELobbyLogin);
    }

    public void OnEvent(StaticDataLoadSuccessEvent e)
    {
        load = true;
        //加载数据
        StaticDataMgr.instance.LoadData(StaticDataUtil.instance.gameConfig);
        LoadServerList();
        Login(userName, password, nickName, club);
    }

    public override void Destroy()
    {
        base.Destroy();
        NetMgr.UnRegister(ProxyModelIndex.PlayerPM, OnPlayerPMUpdate);
    }
}
